package com.koala.upms.service.impl;


import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.koala.common.core.vo.MenuVO;
import com.koala.upms.api.entity.SysRole;
import com.koala.upms.api.entity.SysUser;
import com.koala.upms.mapper.SysUserMapper;
import com.koala.upms.service.SysMenuService;
import com.koala.upms.service.SysRoleService;
import com.koala.upms.service.SysUserService;
import com.koala.upms.api.vo.UserInfo;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author zhangchengji
 * @since 2019-05-11
 */
@Service
@AllArgsConstructor
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    private final SysRoleService sysRoleService;

    private final SysMenuService sysMenuService;

    @Override
    public UserInfo getUserInfo(SysUser user) {
        UserInfo userInfo = new UserInfo();
        userInfo.setUser(user);
        //设置角色id
        List<Integer> roles = sysRoleService.listRolesByUserId(user.getUserId()).stream().map(SysRole::getRoleId).collect(Collectors.toList());
        userInfo.setRoles(ArrayUtil.toArray(roles,Integer.class));
        //获取权限标示
        HashSet<String> permissions = new HashSet<>();
        roles.forEach(roleId -> {
            List<String> permissionList=sysMenuService.getMenuByRoleId(roleId).stream().filter(sysmenu -> StringUtils.isNotEmpty(sysmenu.getPermission())).map(MenuVO::getPermission).collect(Collectors.toList());
            permissions.addAll(permissionList);
        } );
        userInfo.setPermissions(ArrayUtil.toArray(permissions,String.class));
        return userInfo;
    }
}
